Page({
  data: {
    contractInfo: null,
    showActions: false,
    canSign: false
  },

  onLoad(options) {
    const { id } = options
    this.getContractDetail(id)
  },

  // 获取合同详情
  getContractDetail(id) {
    wx.showLoading({ title: '加载中' })
    wx.request({
      url: `your-api-url/contract/detail/${id}`,
      success: (res) => {
        const contractInfo = res.data
        // 处理状态显示样式
        contractInfo.statusClass = this.getStatusClass(contractInfo.status)
        contractInfo.statusText = this.getStatusText(contractInfo.status)
        
        // 检查当前用户是否需要签署
        const userInfo = wx.getStorageSync('userInfo')
        const needSign = contractInfo.signers.find(
          signer => signer.userId === userInfo.userId && !signer.signed
        )

        this.setData({
          contractInfo,
          showActions: true,
          canSign: !!needSign
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 获取状态样式类
  getStatusClass(status) {
    const statusMap = {
      0: 'status-pending',
      1: 'status-processing',
      2: 'status-completed'
    }
    return statusMap[status] || 'status-pending'
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: '待签署',
      1: '签署中',
      2: '已完成'
    }
    return statusMap[status] || '待签署'
  },

  // 下载合同
  downloadContract() {
    const { fileUrl } = this.data.contractInfo
    wx.showLoading({ title: '下载中' })
    wx.downloadFile({
      url: fileUrl,
      success: (res) => {
        wx.openDocument({
          filePath: res.tempFilePath,
          success: () => {
            wx.hideLoading()
          }
        })
      },
      fail: () => {
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })
  },

  // 签署合同
  signContract() {
    wx.navigateTo({
      url: `/pages/signature/signature?contractId=${this.data.contractInfo.id}`
    })
  }
}) 